package com.jszc.lottery.common.datatest;

import java.lang.reflect.Method;

/**
 * 枚举辅助工具
 */
public class EnumUtil {
    /**
     * 把枚举code值转化成指定枚举
     */
    public  static <TE> TE valueOf(Class<TE> cls,Object code){
        if(!cls.isEnum()){
            throw new CommonException(String.format("[%s]不是枚举",cls.getName()));
        }
        try {
            TE[] enums = cls.getEnumConstants();
            Method codeMethod = cls.getMethod("getCode");
            for(TE e : enums){
                if(codeMethod.invoke(e).equals(code)){
                    return e;
                }
            }
            throw new CommonException(String.format("没有找到对应枚举值[%s]",code.toString()));
        } catch (Exception e) {
            throw new CommonException("Enum转化异常",e);
        }
    }

    /**
     * 获取枚举编码
     */
    public static <TE> Object getCode(TE enumValue){
        if(enumValue == null || !enumValue.getClass().isEnum()){
            throw new CommonException("非法枚举值");
        }
        try {
            Method codeMethod = enumValue.getClass().getMethod("getCode");
            return codeMethod.invoke(enumValue);
        } catch (Exception e) {
            throw new CommonException("调用枚举getCode时异常", e);
        }
    }
}
